/**
 * 
 */
package net.mikoo.seals.boss.common.helper;

import java.util.ArrayList;
import java.util.List;

import net.mikoo.seals.boss.model.Geo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


/**
 * @author huangxm
 *
 */
public class GeoHelper{
	
	public static List<Geo> convertToTreeList(List<Geo> datas,Long primaryId){
		
		List<Geo> parents = loadSubs(datas,primaryId);
		for (Geo geo : parents) {
			List<Geo> subs = loadSubs(datas,geo.getGeoId());
			if(subs!= null && !subs.isEmpty()){
				geo.setChilds(subs);
				convertToTreeList(datas,geo.getGeoId());
			}
		}
		return parents;
	}
	
	public static JSONArray convertToJsonTreet(List<Geo> datas,Long primaryId){
		
		JSONArray jsonArray  = new JSONArray();
		List<Geo> parents = loadSubs(datas,primaryId);
		for (Geo geo : parents) {
			JSONObject json = new JSONObject();
			json.put("geoId", geo.getGeoId());
			json.put("parentId", geo.getParentId());
			json.put("geoName", geo.getGeoName());
			
			List<Geo> subs = loadSubs(datas,geo.getGeoId());
			if(subs!= null && !subs.isEmpty()){
				json.put("childs", convertToJsonTreet(datas,geo.getGeoId()));
			}
			jsonArray.add(json);
		}
		
		return jsonArray;
	}
	
	public static JSONArray convertToJsonTreet1(List<Geo> datas,Long primaryId){
		
		JSONArray jsonArray  = new JSONArray();
		List<Geo> parents = loadSubs(datas,primaryId);
		for (Geo geo : parents) {
			JSONObject json = new JSONObject();
			json.put("value", geo.getGeoId());
			json.put("name", geo.getGeoName());
			
			List<Geo> subs = loadSubs(datas,geo.getGeoId());
			if(subs!= null && !subs.isEmpty()){
				json.put("children", convertToJsonTreet1(datas,geo.getGeoId()));
			}
			jsonArray.add(json);
		}
		
		return jsonArray;
	}
	
	
	public static List<Geo> convertToTree(List<Geo> childs,Long primaryId,int level){
		
		List<Geo> geos = new ArrayList<Geo>();
		String str = "";
		int index = 0;
		for (Geo geo : childs) {
			
			if(geo.getParentId().equals(primaryId)){
				index++;
				List<Geo> subs = loadSubs(childs,primaryId);
				for (int i = 0; i < level; i++) {

					if (i + 1 == level) {

						if (index == subs.size()) {
							str = str + "\u0008 \u0008 \u0008└─";
						} else {
							str = str + "\u0008 \u0008 \u0008├─";
						}
					} else {

						str = str + "\u0008 \u0008 \u0008│";

					}

				}
				geo.setGeoName(str+" "+geo.getGeoName());
				geo.setChilds(subs);
				geos.add(geo);str = "";
				if(subs.size()>0){
					geos.addAll(convertToTree(childs,geo.getGeoId(),level+1));
				}
			}
		}
		
		return geos;
	}
	
	/**
	 * 查询子类
	 * @param Geos
	 * @param primaryId
	 * @return
	 */
	public static List<Geo> loadSubs(List<Geo> geos,Long primaryId){
		List<Geo> childs = new ArrayList<Geo>();
		
		for (Geo Geo : geos) {
			if(Geo.getParentId().equals(primaryId)){
				childs.add(Geo);
			}
		}
		return childs;
	}
	
	
}
